export class Snake{
    head:HTMLElement;//头
    bodies:HTMLCollectionOf<HTMLElement>;//身体（包括蛇头）
    element:HTMLElement;
    constructor(){
        this.element = document.getElementById('snack')!
        this.head = document.querySelector('#snack > div')!
        this.bodies = this.element.getElementsByTagName('div')
    }

    //获取坐标
    get x(){
        return this.head.offsetLeft
    }
    get y(){
        return this.head.offsetTop
    }

    set x(val){
        if(this.x === val) return
        //修改x值，左右移动，向左不能向右走 反之亦然(放在判断撞墙前)
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === val){
            // console.log("水平掉头");
            if(val > this.x){
                //蛇往右 调头 应该继续向左？修正
                val = this.x - 10
            }else{
                val = this.x + 10
            }
        }
        //是否撞墙
        if(val < 0 || val > 290){
            throw new Error("蛇死了")
        }
        this.moveBody()
        this.head.style.left = val + 'px'
        this.checkHeadBody()
    }
    set y(val){
        if(this.y === val) return
        if(val < 0 || val > 290){
            throw new Error("蛇死了")
        }
        //这样写会超出边界20px
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === val){
            if(val > this.y){
                val = this.y - 10
            }else{
                val = this.y + 10
            }
        }
        this.moveBody()
        this.head.style.top = val + 'px'
        this.checkHeadBody()
    }
    //蛇增加身体
    addBody(){
        this.element.insertAdjacentHTML('beforeend',"<div></div>")
    }
    //添加蛇身体移动方法
    moveBody(){
        //将后边的身体设置为前面的位置
        //遍历获取所有身体
        for(let i = this.bodies.length -1;i > 0;i--){
            let x = (this.bodies[i-1] as HTMLElement).offsetLeft;
            let y = (this.bodies[i-1] as HTMLElement).offsetTop;
            //设置到当前身体
            (this.bodies[i] as HTMLElement).style.left = x + 'px';
            (this.bodies[i] as HTMLElement).style.top = y + 'px';
        }
    }
    //判断是否撞到自己
    checkHeadBody(){
        for(let i = 4;i < this.bodies.length;i++){
            if(this.x === this.bodies[i].offsetLeft && this.y === this.bodies[i].offsetTop){
                //相撞了
                throw new Error('撞到自己啦！')
            }
        }
    }
}